#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define PORT 12345

struct User {
  char username[50];
  char password[50];
};

int authenticate_user(struct User user) {
  // 实现用户认证逻辑，比较用户名和密码
  if (strcmp(user.username, "example_user") == 0 && strcmp(user.password, "password123") == 0) {
    return 1; // 认证成功
  } else {
    return 0; // 认证失败
  }
}

int main() {
  int server_socket, client_socket;
  struct sockaddr_in server_addr, client_addr;
  socklen_t addr_size;

  struct User user;
  strcpy(user.username, "zsy");
  strcpy(user.password, "123456");

  server_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (server_socket == -1) {
    perror("Socket creation failed");
    exit(EXIT_FAILURE);
  }

  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT);
  server_addr.sin_addr.s_addr = INADDR_ANY;

  if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
    perror("Binding failed");
    exit(EXIT_FAILURE);
  }

  if (listen(server_socket, 5) == -1) {
    perror("Listening failed");
    exit(EXIT_FAILURE);
  }

  printf("Server listening on port %d\n", PORT);

  addr_size = sizeof(client_addr);
  client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &addr_size);
  if (client_socket == -1) {
    perror("Accepting connection failed");
    exit(EXIT_FAILURE);
  }

  printf("Connection established\n");

  // 用户认证
  struct User received_user;
  recv(client_socket, &received_user, sizeof(received_user), 0);

  if (authenticate_user(received_user)) {
    send(client_socket, "Authentication successful", strlen("Authentication successful"), 0);
  } else {
    send(client_socket, "Authentication failed", strlen("Authentication failed"), 0);
    close(client_socket);
    close(server_socket);
    exit(EXIT_SUCCESS);
  }

  char message[1024];

  while (1) {
    recv(client_socket, message, sizeof(message), 0);
    printf("Received message: %s\n", message);

    printf("Enter your response: ");
    fgets(message, sizeof(message), stdin);
    send(client_socket, message, strlen(message), 0);
  }

  close(client_socket);
  close(server_socket);

  return 0;
}
